import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
import uvicorn

from app.core.config import settings
from app.api.v1.colorize import router as colorize_router
from app.api.v1.health import router as health_router

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager"""
    # Startup
    logger.info("Starting Manga Colorizer API...")
    logger.info(f"Environment: {'development' if settings.debug else 'production'}")
    logger.info(f"Storage type: {settings.storage_type}")
    logger.info(f"Model device: {settings.device}")
    
    yield
    
    # Shutdown
    logger.info("Shutting down Manga Colorizer API...")


# Create FastAPI app
app = FastAPI(
    title="Manga Colorizer API",
    description="AI-powered manga sketch colorization service",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure appropriately for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Mount static files for local storage
if settings.storage_type == "local":
    from pathlib import Path
    uploads_path = Path(settings.model_path).parent / "uploads"
    uploads_path.mkdir(parents=True, exist_ok=True)
    app.mount("/static", StaticFiles(directory=str(uploads_path)), name="static")

# Include routers
app.include_router(colorize_router, prefix="/api/v1")
app.include_router(health_router, prefix="/api/v1")

# Root endpoint
@app.get("/", include_in_schema=False)
async def root():
    """Redirect to API documentation"""
    return RedirectResponse(url="/docs")


@app.get("/api")
async def api_info():
    """API information endpoint"""
    return {
        "name": "Manga Colorizer API",
        "version": "1.0.0",
        "description": "AI-powered manga sketch colorization service",
        "endpoints": {
            "docs": "/docs",
            "health": "/api/v1/health",
            "colorize": "/api/v1/colorize"
        }
    }


if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level="info"
    )
